# -*- coding: utf-8 -*-
import datetime 

from django import forms

from client.models import Clients, Regions

ERROR_MESSAGES = {
    "password_match": "Пароли не совпадают!",
    "incorrect_name_length": "Имя не может содержать менее 3-ёх символов и более 20-ти!",
    "email_already_exist": "Пользователь с таким email-ом уже существует!",
    "city_is_not_selected": "Пожалуйста, выберите Ваш город!",
}

class RegistrationForm(forms.ModelForm):
    company = forms.CharField(max_length=255, required=False)
    email = forms.EmailField()
    patronymic = forms.CharField(max_length=50, required=False)
    regions = forms.ModelChoiceField(queryset=Regions.objects.all())
    confirm_password = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        if len(args):
            self.city_id = args[0].dict().get("city_id")

    def clean(self):
        super(RegistrationForm, self).clean()
        password = self.cleaned_data.get("password")
        confirm_password = self.cleaned_data.get("confirm_password")

        if not self.city_id:
            raise forms.ValidationError(ERROR_MESSAGES.get("city_is_not_selected"))

        if password != confirm_password:
            raise forms.ValidationError(ERROR_MESSAGES.get("password_match"))

        return self.cleaned_data


    def clean_name(self):
        name = self.cleaned_data.get("name")
        if len(name) < 3 or len(name) > 20:
            raise forms.ValidationError(ERROR_MESSAGES.get("incorrect_name_length"))

        return name

    def clean_email(self):
        email = self.cleaned_data.get("email")

        if Clients.objects.filter(name=email):
            raise forms.ValidationError(ERROR_MESSAGES.get("email_already_exist"))

        return email



    def save(self, commit=True):
        m = super(RegistrationForm, self).save(commit=False)
        m.city_id = self.city_id
        m.date_registration = datetime.datetime.now()
        m.last_activity = m.date_registration
        m.save()

    class Meta:
        model = Clients
        fields = (
            'name', 'surname', 'patronymic', 'email',
            'password', 'confirm_password', 'company'
        )
